package com.eco.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.bean.Users;
import com.eco.service.RedisService;
import com.eco.service.UsersService;
import com.eco.util.DeCodeUtil;
import com.eco.util.JWTUtil;
import com.eco.util.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("users")
@CrossOrigin
public class UserController {
    @Autowired
    UsersService usersService;

    @Autowired
    RedisService redisService;

    @GetMapping("list")
    public Result getlist(){
        List<Users> list = usersService.list();
        return Result.success(list);
    }

    @PostMapping("/")
    public Result add(@RequestBody Users users){
        users.setPasswordHash("123123");
        String pass=users.getPasswordHash();
        String newpass= DeCodeUtil.decode(pass);
        users.setPasswordHash(newpass);
        usersService.save(users);
        Users admin = usersService.getById(users.getId());
        return Result.success("保存成功",admin);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") String id){
        boolean b=usersService.removeById(id);
        if(b){
            return Result.success("删除成功",null);
        }
        else{
            return Result.fail(201,"删除失败");
        }
    }
    @PutMapping
    public Result edit(@RequestBody Users users){
        Boolean b=usersService.saveOrUpdate(users);
        Users users1=usersService.getById(users.getId());
        if (b){
            return Result.success("保存成功",users1);
        }
        else{
            return Result.fail(500,"保存失败");
        }
    }

    @PostMapping("login")
    public Result login( Users user, @RequestParam ("captcha") String captcha, @RequestParam ("captchakey") String captchakey) {
        //验证码是否正确
        String captchacheck = checkCaptcha(captchakey,captcha);
        if(!captchacheck.equals("success")){
            return Result.fail(402,captchacheck);
        }
        // 用户名查询用户信息
        Users user_data = usersService.selectByphone(user.getPhone());

        // 如果有信息，对比密码是否正确
        if (user_data != null) {
            // 加密前端传入的数据和数据库密码进行比较
            String encryptedPassword = DeCodeUtil.decode(user.getPasswordHash());
            boolean check = encryptedPassword.equals(DeCodeUtil.decode(user_data.getPasswordHash()));
            if (check) {
                // 对比正确登录成功，签发token
                String token = JWTUtil.getToken();
                return Result.success("登陆成功", token);
            }
        }

        return Result.fail(401, "认证失败");
    }

    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchText") String searchText) {
        IPage<Users> result;

        if (searchText == null || searchText.isEmpty()) {
            result = usersService.page(page);
        } else {
            QueryWrapper<Users> wrapper = new QueryWrapper<Users>();
            wrapper.like("username", searchText)

                    .or().like("role", searchText);

            result = usersService.page(page, wrapper); // ✅ 使用 wrapper 查询
        }

        return Result.success(result);
    }
    private String checkCaptcha(@RequestParam("captchakey") String captchakey,@RequestParam("captchaCode") String captchaCode) {

        if(captchakey==null){
            return "请求参数异常";
        }
        String code = (String) redisService.get(captchakey);
        if(code==null){
            return "验证码过期";
        }
        if(captchaCode.equalsIgnoreCase(code)) {
            return "success";
        }
        return "验证码验证失败";
    }
}
